package cn.melonlib.specials.auth.comp.service;

import cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService;
import cn.melonlib.cores.jpa.model.bean.impl.DefaultQuery;
import cn.melonlib.specials.auth.model.entity.Account;
import cn.melonlib.specials.auth.model.entity.Administrator;
import cn.melonlib.specials.auth.model.enums.AccountType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdministratorService extends WorkerBasicService<Administrator> {

    @Resource
    private AccountManagerService accountManagerService;

    public Administrator createAdmin(Administrator administrator,String password
    ) throws Exception{
        String validAdmin="from Administrator where code=?1";
        List<Administrator> administrators=dao.<List<Administrator>,DefaultQuery>search(new DefaultQuery(validAdmin,List.of(administrator.getCode()))).getResult();
        if(administrators.size()>0){
            return null;
        }
        administrator=dao.save(administrator).getResult();
        Account account=new Account();
        account.setAccount(administrator.getCode());
//        account.setTenant("melonlib");
        account.setTenantId("melonlib.cn");
        account.setTenantCode("melonlib.cn");
        account.setActivated(true);
        account.setAccountTypes(getJsonMapper().writeValueAsString(List.of(AccountType.ADMIN.name())));
        accountManagerService.createAccount(account,password);
        return administrator;
    }
}
